const {
  request
} = require("../../utils/asyncWX");

// pages/placeOrder/placeOrder.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    rootShow: false,
    activeNames: ['1'],
    currentIndex: 1,
    currentBuildIndex: -1,
    buildValue: '请选择',
    currentFloorIndex: -1,
    floorValue: '请选择',
    currentRoomIndex: -1,
    roomValue: '请选择',
    currentNum: 1,
    notice: '',
    selectValue: 1,
    value: 1,
    price: '计算中...',
    building_no: '',
    buildingArr: [],
    floor_no: '',
    floorArr: [],
    room_no: '',
    roomObj: {},
    oldRoomObj: {},
    disabledIpt: true,
    loading: false,
    nf_price: '',
    jt_price: '',
    bucketArray:0,//桶的数量上线
    nf_name:'品牌1',
    nf_num:'',
    jt_name:'品牌2',
    jt_num:'',

  },
  // 控制折叠面板
  onChange(event) {
    if (event.detail == '4') {
      if (this.data.building_no == '') {
        this.setData({
          activeNames: [],
        });
        return wx.showToast({
          title: '请先选择公寓',
          icon: 'none'
        })
      }
      this.setData({
        activeNames: event.detail,
      });
    } else if (event.detail == '5') {
      if (this.data.floor_no == '') {
        this.setData({
          activeNames: [],
        });
        return wx.showToast({
          title: '请先选择楼层',
          icon: 'none'
        })
      }
      this.setData({
        activeNames: event.detail,
      });
    }
    this.setData({
      activeNames: event.detail,
    });
  },

  // 输入框获取焦点时做什么
  handleFocus(e) {
    this.setData({
      activeNames: '5',
    });
  },

  // 防止点击穿透
  catchTab() {
    console.log('请输入房间号');
  },

  // 页面首次加载时执行的函数
  onLoad() {
    const token = wx.getStorageSync('token')
    if (!token) {
      wx.navigateTo({
        url: '/pages/login/login?msg=请先登录',
      })
      return
    }
    this.getNotice()
    this.getBuildList()
    this.getPrice()
  },

  // 搜索房间
  handleInput(val) {
    const room_no = val.detail.value
    if (room_no.length == 0) {
      this.setData({
        roomObj: this.data.oldRoomObj
      })
      return
    }
    const arr = []
    const roomObj = JSON.parse(JSON.stringify(this.data.oldRoomObj))
    for (const key in roomObj) {
      if (Object.hasOwnProperty.call(roomObj, key)) {
        const el = roomObj[key];
        if (el.room_no.indexOf(room_no) !== -1) {
          arr.push(el)
        }
      }
    }
    this.setData({
      roomObj: arr
    })
  },

  // 选择房间号
  handleRoomNum(e) {
    this.setData({
      currentRoomIndex: e.currentTarget.dataset.index,
      roomValue: e.currentTarget.dataset.room,
      room_no: e.currentTarget.dataset.room,
      price: '16 元'
    })
  },

  // 选择楼层
  handleFloorNum(e) {
    this.setData({
      currentFloorIndex: e.currentTarget.dataset.index,
      floorValue: e.currentTarget.dataset.floor,
      floor_no: e.currentTarget.dataset.floor,
      disabledIpt: false
    })
    this.getRoomList(this.data.building_no, e.currentTarget.dataset.floor)
  },

  // 选择公寓
  handleBuildNum(e) {
    this.setData({
      currentBuildIndex: e.currentTarget.dataset.index,
      buildValue: e.currentTarget.dataset.build,
      building_no: e.currentTarget.dataset.build
    })
    this.getFloorList(e.currentTarget.dataset.build)
  },

  // 获取公告
  async getNotice() {
    try {
      const res = await request({
        url: '/api/getNotice',
        data: {},
        method: 'post'
      })
      // console.log(res);
      if (res.data.code == 200) {
        this.setData({
          notice: res.data.data
        })
      }
    } catch (error) {
      console.log(error);
      wx.showToast({
        title: '获取公告出错',
        icon: 'none'
      })
    }
  },

  // 选择品牌
  handleChangeIndex(e) {
    const index = e.currentTarget.dataset.index
    const _this = this
    if(index == 1){
        this.setData({
            bucketArray:_this.data.nf_num,
            currentIndex: index,
            selectValue: index,
            value:1,
            currentNum:1
        })
    }else{
        this.setData({
            bucketArray:_this.data.jt_num,
            currentIndex: index,
            selectValue: index,
            value:1,
            currentNum:1
        })
    }
  },

  // 选择数量
  handleChangeNum(e) {
    const index = e.currentTarget.dataset.index
    // const price = this.data.selectValue=='王子山泉'?this.data.nf_price:this.data.selectValue=='长寿山泉'?this.data.jt_price:0
    // const total_price = Number(index) * Number(price)
    // console.log(total_price);
    this.setData({
      currentNum: index,
      value: index
    })
  },

  // 获取公寓
  async getBuildList() {
    try {
      const res = await request({
        url: '/back/getAllBuilding',
        data: {
          status: 1
        },
        method: 'post'
      })
      if (!res) return
      if (res.data.code == 200) {
        this.setData({
          buildingArr: res.data.data
        })
      }
    } catch (error) {
      console.log(error);
      wx.showToast({
        title: '获取公寓出错',
        icon: 'none'
      })
    }
  },

  // 获取楼层
  async getFloorList(building_no) {
    try {
      const res = await request({
        url: '/back/getAllFloor',
        data: {
          building_no,
          status: 1
        },
        method: 'post',
        loading: true
      })
      if (!res) return
      if (res.data.code == 200) {
        this.setData({
          floorArr: res.data.data
        })
      }
    } catch (error) {
      console.log(error);

    }
  },

  // 获取房间号
  async getRoomList(building_no, floor_no) {
    try {
      const res = await request({
        url: '/back/getAllRoom',
        data: {
          building_no,
          floor_no,
          status: 1
        },
        method: 'post',
        loading: true
      })
      if (!res) return
      if (res.data.code == 200) {
        this.setData({
          roomObj: res.data.data,
          oldRoomObj: res.data.data
        })
      }
    } catch (error) {
      console.log(error);

    }
  },

  // 下单前判断有东西没填
  check() {
    const _this = this.data
    if (_this.selectValue === -1) {
        wx.showToast({
            title: '暂不支持下单操作',
            icon: 'none'
          })
          return false
    }
    if (_this.selectValue == '' || _this.value == '') {
      wx.showToast({
        title: '请选择品牌和数量',
        icon: 'none'
      })
      return false
    }
    if (_this.building_no == '') {
      wx.showToast({
        title: '请选择公寓',
        icon: 'none'
      })
      return false
    }
    if (_this.floor_no == '') {
      wx.showToast({
        title: '请选择楼层',
        icon: 'none'
      })
      return false
    }
    if (_this.room_no == '') {
      wx.showToast({
        title: '请选择房间号',
        icon: 'none'
      })
      return false
    }
    return true
  },

  // 点击下单
  async handlePayment() {
    
    this.setData({
      loading: true
    })
    wx.showLoading({
      title: '订单创建中...',
      mask: true
    })
    const _this = this.data
    const that = this
    const data = {
      building_no: _this.building_no,
      floor_no: _this.floor_no,
      room_no: _this.room_no,
      water_type: _this.selectValue,
      num: _this.value,
    }
    try {
      const res = await request({
        url: '/api/createOrder',
        data,
        method: 'post'
      })
      if (!res) {
        this.setData({
          loading: false
        })
        return
      }
      if (res.data.code == 200) {
        that.pay(res.data.data.id)
      } else {
        this.setData({
          loading: false
        })
      }
    } catch (error) {
      // console.log(error);
      wx.hideLoading()
      wx.showToast({
        title: '下单时出错啦',
        icon: 'none'
      })
      this.setData({
        loading: false
      })
    } 
  },

  // 确认订单 -- 支付
  confirmOrder(data) {
    const _this = this.data
    const that = this
    if (!this.check()) return
    let brandName = " "
    if(_this.selectValue == 1){
        brandName =  _this.nf_name
    }else{
        brandName = _this.jt_name
    }
	if(_this.building_no == 100 ){
		wx.showModal({
		  title: '确认订单',
		  content: `品牌：${brandName} \r\n 数量：${_this.value} 桶 \r\n 公寓：教师公寓 \r\n 楼层：${_this.floor_no} 楼 \r\n 房间号：${_this.room_no} 房\r\n`,
		  success(res) {
		    if (res.confirm) {
		      that.handlePayment()
		    } else if (res.cancel) {
		      console.log('用户点击取消')
		      that.setData({
		        loading: false
		      })
		    }
		  }
		})
	}else if(_this.building_no == 101){
		wx.showModal({
		  title: '确认订单',
		  content: `品牌：${brandName} \r\n 数量：${_this.value} 桶 \r\n 公寓：培训大楼 \r\n 楼层：${_this.floor_no} 楼 \r\n 房间号：${_this.room_no} 房\r\n`,
		  success(res) {
		    if (res.confirm) {
		      that.handlePayment()
		    } else if (res.cancel) {
		      console.log('用户点击取消')
		      that.setData({
		        loading: false
		      })
		    }
		  }
		})
	}else{
		wx.showModal({
		  title: '确认订单',
		  content: `品牌：${brandName} \r\n 数量：${_this.value} 桶 \r\n 公寓：${_this.building_no} 栋 \r\n 楼层：${_this.floor_no} 楼 \r\n 房间号：${_this.room_no} 房\r\n`,
		  success(res) {
		    if (res.confirm) {
		      that.handlePayment()
		    } else if (res.cancel) {
		      console.log('用户点击取消')
		      that.setData({
		        loading: false
		      })
		    }
		  }
		})
	}
	
  },

  // 后端支付接口
  async pay(order_id) {
    wx.showLoading({
      title: '支付中...',
      mask: true
    })
    try {
      const res = await request({
        url: '/api/pay',
        data: {
          order_id
        },
        method: 'post'
      })
      if (!res) {
        this.setData({
          loading: false
        })
        return
      }
      if (res.data.code == 200) {
        this.wxPay(res.data.data)
      } else {
        this.setData({
          loading: false
        })
      }
    } catch (error) {
      console.log(error);
      wx.showToast({
        title: '支付前出错啦',
        icon: 'none'
      })
      this.setData({
        loading: false
      })
    } finally {
      // wx.hideLoading()
    }
  },

  // 调起微信支付
  wxPay(data) {
    const _this = this
    wx.requestPayment({
      nonceStr: data.nonceStr,
      package: data.package,
      signType: data.signType,
      paySign: data.paySign,
      timeStamp: data.timeStamp,
      success(res) {
        wx.showToast({
          title: '支付成功',
          icon: 'none'
        })
        _this.setData({
          loading: false
        })
        setTimeout(() => {
          wx.switchTab({
            url: '/pages/user/user',
          })
        }, 1000)
      },
      fail(res) {
        wx.showToast({
          title: '取消支付',
          icon: 'none'
        })
        _this.setData({
          loading: false
        })
      }
    })
  },

  // 获取商品单价
  async getPrice() {
    try {
      const res = await request({
        url: '/api/getPrice',
        data: {},
        method: 'post'
      })
      if (!res) return
      if (res.data.code == 200) {
          console.log(res.data.data)
        // res.data.data.nf_price
        const nf_price = Number(res.data.data.nf_price)
        const jt_price = Number(res.data.data.jt_price)
        let index = 1
        if (nf_price <= 0 && jt_price > 0) index = 2
        else if (jt_price <= 0 && nf_price > 0) index = 1
        else if (nf_price<=0&&nf_price<=0) index =-1
        else index = 1
        this.setData({
          nf_price,
          jt_price,
          nf_num:res.data.data.nf_num,
          jt_num:res.data.data.jt_num,
          nf_name:res.data.data.nf_name,
          jt_name:res.data.data.jt_name,
          bucketArray:index == 1 ? res.data.data.nf_num : res.data.data.jt_num,
          currentIndex: index,
          selectValue: index 
        })
      }
    } catch (error) {
      console.log(error);
    }
  },
})